package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.blankj.utilcode.util.TimeUtils;
import com.contrarywind.adapter.WheelAdapter;
import com.contrarywind.view.WheelView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.SignInRecordAdapter;
import flc.ast.bean.MyCalendarBean;
import flc.ast.bean.MySignInRecordBean;
import flc.ast.databinding.ActivitySignInRecordBinding;
import flc.ast.utils.AppSpUtils;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StatusBarUtils;

public class SignInRecordActivity extends BaseAc<ActivitySignInRecordBinding> {

    private SignInRecordAdapter recordAdapter;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
    private Dialog mySelYearDialog;
    private WheelView wheelView1;


    @Override
    protected int onCreate() {
        return R.layout.activity_sign_in_record;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivSignInRecordBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.rvSignInRecordList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        recordAdapter = new SignInRecordAdapter();
        mDataBinding.rvSignInRecordList.setAdapter(recordAdapter);
        mDataBinding.tvYear.setOnClickListener(this);
        //选择年份弹框
        selYearDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvYear://选择年月
                mySelYearDialog.show();
                break;
            //选择日期弹框
            case R.id.tvDialogSelYearCancel://取消
                mySelYearDialog.dismiss();
                break;
            case R.id.tvDialogSelYearRight://确定
                mySelYearDialog.dismiss();
                int year = wheelView1.getCurrentItem() + 1980;
                String selDate = year + "年";
                mDataBinding.tvYear.setText(selDate);
                setDay(year);//设置日历
                break;
        }
    }

    @Override
    protected void initData() {
        //获取当前年份
        int year = Integer.parseInt(TimeUtils.getNowString(new SimpleDateFormat("yyyy")));
        int moon = Integer.parseInt(TimeUtils.getNowString(new SimpleDateFormat("M")));//获取当前月份
        int day = Integer.parseInt(TimeUtils.getNowString(new SimpleDateFormat("d")));//获取当前天数
        mDataBinding.tvYear.setText(TimeUtils.getNowString(new SimpleDateFormat("yyyy年")));//当前年月
        setDay(year);
    }

    //设置日历数据
    private void setDay(int year) {
        showDialog(getString(R.string.get_sign_in_ing));
        RxUtil.create(new RxUtil.Callback<List<MySignInRecordBean>>() {
            @Override
            public void doBackground(ObservableEmitter<List<MySignInRecordBean>> emitter) {
                List<MySignInRecordBean> list = new ArrayList<>();
                for (int i = 0; i < 12; i++) {
                    List<MyCalendarBean> day = getDay(i + 1, year);
                    switch (i) {
                        case 0:
                            list.add(new MySignInRecordBean(getString(R.string.january), day));
                            break;
                        case 1:
                            list.add(new MySignInRecordBean(getString(R.string.february), day));
                            break;
                        case 2:
                            list.add(new MySignInRecordBean(getString(R.string.march), day));
                            break;
                        case 3:
                            list.add(new MySignInRecordBean(getString(R.string.april), day));
                            break;
                        case 4:
                            list.add(new MySignInRecordBean(getString(R.string.may), day));
                            break;
                        case 5:
                            list.add(new MySignInRecordBean(getString(R.string.june), day));
                            break;
                        case 6:
                            list.add(new MySignInRecordBean(getString(R.string.july), day));
                            break;
                        case 7:
                            list.add(new MySignInRecordBean(getString(R.string.august), day));
                            break;
                        case 8:
                            list.add(new MySignInRecordBean(getString(R.string.september), day));
                            break;
                        case 9:
                            list.add(new MySignInRecordBean(getString(R.string.october), day));
                            break;
                        case 10:
                            list.add(new MySignInRecordBean(getString(R.string.november), day));
                            break;
                        case 11:
                            list.add(new MySignInRecordBean(getString(R.string.december), day));
                            break;
                    }
                }
                emitter.onNext(list);
            }

            @Override
            public void accept(List<MySignInRecordBean> list) {
                recordAdapter.setList(list);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        dismissDialog();
                    }
                }, 1000);
            }
        });
    }

    //设置日期数据
    private List<MyCalendarBean> getDay(int moon, int year) {
        //获取天数
        int dayNum = getDayNum(moon, year);
        //获取需要空出的天数
        int weekNum = getWeekNum(moon, year);
        //生成日历表
        List<MyCalendarBean> listDay = new ArrayList<>();
        for (int i = 0; i < 42; i++) {
            if (i <= weekNum || i > dayNum + weekNum) {
                listDay.add(new MyCalendarBean("", i, false, false));//空
            } else {
                listDay.add(new MyCalendarBean(i - weekNum + "", i, false, false));
            }
        }
        List<String> listSp = AppSpUtils.getSignIntList();
        for (MyCalendarBean bean : listDay) {
            if (!TextUtils.isEmpty(bean.getDate())) {
                String nowDate = year + "." + moon + "." + bean.getDate();
                if (nowDate.equals(TimeUtils.getNowString(new SimpleDateFormat("yyyy.M.d")))) {
                    bean.setSelect(true);
                }
            }
            if (listSp != null && listSp.size() > 0) {
                for (String s : listSp) {
                    long millis1 = TimeUtils.string2Millis(s, format);
                    long millis2 = TimeUtils.string2Millis(year + "." + moon + "." + bean.getDate(), new SimpleDateFormat("yyyy.MM.dd"));
                    if (millis1 == millis2) {
                        bean.setRecord(true);
                        break;
                    }
                }
            }
        }
        return listDay;
    }

    //判断该月有多少天
    private int getDayNum(int moon, int year) {
        int dayNum = 31;
        if (moon == 1 || moon == 3 || moon == 5 || moon == 7 || moon == 8 || moon == 10 || moon == 12) {
            //大月31天
            dayNum = 31;
        } else if (moon == 2) {
            //2月判断是闰(29)还是平(28)
            if ((year % 4 == 0 && year % 100 != 0 || (year % 400 == 0))) {
                dayNum = 29;
            } else {
                dayNum = 28;
            }
        } else {
            //小月30天
            dayNum = 30;
        }
        return dayNum;
    }

    //获取该月第一天是星期几（当天要算上 所以少减一天）
    private int getWeekNum(int moon, int year) {
        int weekNum = 0;
        String week = TimeUtils.getChineseWeek(year + "." + moon + ".01", format);
        if (week.equals(getString(R.string.monday_text))) {
            weekNum = 0;
        } else if (week.equals(getString(R.string.tuesday_text))) {
            weekNum = 1;
        } else if (week.equals(getString(R.string.wednesday_text))) {
            weekNum = 2;
        } else if (week.equals(getString(R.string.thursday_text))) {
            weekNum = 3;
        } else if (week.equals(getString(R.string.friday_text))) {
            weekNum = 4;
        } else if (week.equals(getString(R.string.saturday_text))) {
            weekNum = 5;
        } else if (week.equals(getString(R.string.sunday_text))) {
            weekNum = 6;
        }
        return weekNum;
    }

    //选择年份弹框
    private void selYearDialog() {
        mySelYearDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_sel_year, null);
        mySelYearDialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = mySelYearDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics dm = getResources().getDisplayMetrics();
        lp.width = (int) (dm.widthPixels * 1);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView dialogCancel = inflate.findViewById(R.id.tvDialogSelYearCancel);
        TextView dialogRight = inflate.findViewById(R.id.tvDialogSelYearRight);
        wheelView1 = inflate.findViewById(R.id.wheel_view1);
        dialogCancel.setOnClickListener(this);
        dialogRight.setOnClickListener(this);
        wheelView1.setDividerColor(Color.parseColor("#66457096"));
        wheelView1.setTextColorCenter(Color.parseColor("#0F3C73"));
        wheelView1.setLineSpacingMultiplier(2.5f);
        wheelView1.setDividerType(WheelView.DividerType.WRAP);
        wheelView1.setDividerColor(Color.parseColor("#4DFF83B3"));
        wheelView1.setCurrentItem(43);
        wheelView1.setItemsVisibleCount(3);
        wheelView1.setCyclic(true);
        wheelView1.setTextSize(16);
        wheelView1.setTypeface(Typeface.DEFAULT_BOLD);
        //设置滚轮数据
        List<String> listYear = new ArrayList<>();//年 1980-2040
        for (int i = 0; i < 61; i++) {
            listYear.add(String.valueOf(1980 + i));
        }
        WheelAdapter adapter1 = new ArrayWheelAdapter(listYear);
        wheelView1.setAdapter(adapter1);
        //滚动到对应日期
        String date = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd"));
        String[] split = date.split("-");
        int year = Integer.parseInt(split[0]);//年
        wheelView1.setCurrentItem(year - 1980);
    }

}